<template>
  <n-card title="视频流分析" :bordered="false">
    <n-space vertical>
      <!-- 顶部操作区域 -->
      <n-space>
        <n-button type="primary" @click="handleCreateTask">创建任务</n-button>
        <CreateVideoTask ref="createTaskModal" />
        <n-input
          v-model:value="searchValue"
          placeholder="请输入任务ID或名称"
          clearable
          style="width: 300px"
        />
        <n-button type="primary" @click="handleSearch">搜索</n-button>
      </n-space>

      <!-- 任务列表 -->
      <n-data-table
        :columns="columns"
        :data="taskList"
        :pagination="pagination"
        :loading="loading"
        :scroll-x="1200"
      />
    </n-space>

    <!-- 任务详情弹窗 -->
    <n-modal v-model:show="showDetailDrawer">
      <n-card style="width: 800px" title="任务详情" :bordered="false">
        <VideoTaskDetail v-if="selectedTask" :task="selectedTask" />
      </n-card>
    </n-modal>

    <!-- 任务模式选择弹窗 -->
    <n-modal v-model:show="selectTaskModeModal">
      <n-card style="width: 800px" title="选择任务模式" :bordered="false">
        <SelectTaskMode @select="handleTaskModeSelect" />
      </n-card>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, ref, reactive, onMounted } from 'vue';
  import { NDataTable, NButton, NTag, NSpace, NInput, useMessage } from 'naive-ui';
  import CreateVideoTask from '@/views/analysis/task/CreateVideoTask.vue';
  import VideoTaskDetail from '@/views/analysis/task/VideoTaskDetail.vue';
  import SelectTaskMode from './SelectTaskMode.vue';
  import { FetchTaskList, CreateTask, DeleteTask, UpdateTaskStatus } from '@/api/analysis/task';

  const message = useMessage();
  const loading = ref(false);
  const searchValue = ref('');
  const showDetailDrawer = ref(false); // 控制详情弹窗显示
  const selectedTask = ref(null); // 选中的任务

  // 创建任务弹窗
  const createTaskModal = ref<InstanceType<typeof CreateVideoTask> | null>(null);
  const selectTaskModeModal = ref<InstanceType<typeof SelectTaskMode> | null>(null);

  // 打开创建任务流程
  function handleCreateTask() {
    createTaskModal.value?.open();
  }

  // 处理任务模式选择
  function handleTaskModeSelect(mode: 'realtime' | 'polling') {
    selectTaskModeModal.value?.open(mode);
  }

  // 设置页面标题
  const setPageTitle = () => {
    document.title = '视频流分析 - 分析中心';
  };

  onMounted(() => {
    setPageTitle();
  });

  // 任务列表数据
  const taskList = ref([]);

  // 分页配置
  const pagination = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [10, 20, 30],
    showQuickJumper: true,
    itemCount: 0, // 添加总条数
    onChange: (page: number) => {
      pagination.page = page;
      getTaskList();
    },
    onUpdatePageSize: (pageSize: number) => {
      pagination.pageSize = pageSize;
      getTaskList();
    },
  });

  // 获取任务列表
  async function getTaskList() {
    try {
      loading.value = true;
      const res = await FetchTaskList({
        page: pagination.page,
        pageSize: pagination.pageSize,
        keyword: searchValue.value.trim(),
      });
      taskList.value = res.list.map((task) => ({
        id: task.id,
        name: task.name,
        status: task.status === 1 ? '运行中' : '已停用',
        task_mode: task.task_mode,
        task_type: task.task_type,
        device_id: task.device_id,
        rtsp_url: task.rtsp_url,
        algorithm_id: task.algorithm_id,
      }));

      pagination.itemCount = res.total;
    } catch (error) {
      message.error('获取任务列表失败');
      taskList.value = [];
    } finally {
      loading.value = false;
    }
  }

  onMounted(() => {
    setPageTitle();
    getTaskList(); // 初始化时获取任务列表
  });

  // 表格列配置
  const columns = ref([
    { title: '任务ID', key: 'id' },
    { title: '任务名称', key: 'name' },
    {
      title: '任务状态',
      key: 'status',
      render(row) {
        const statusMap = {
          1: { label: '运行中', color: 'success' },
          0: { label: '已停用', color: 'error' },
          2: { label: '异常', color: 'warning' },
        };
        const statusConfig = statusMap[row.status] || {
          label: `未知(${row.status})`,
          color: 'default',
        };
        return h(NTag, { type: statusConfig.color }, statusConfig.label);
      },
    },
    {
      title: '任务模式',
      key: 'task_mode',
      render(row) {
        const modeMap = {
          realtime: { label: '实时分析', color: 'warning' },
          polling: { label: '轮询分析', color: 'default' },
        };
        const typeConfig = modeMap[row.task_mode] || { label: '轮询分析', color: 'default' };
        return h(NTag, { type: typeConfig.color }, typeConfig.label);
      },
    },
    {
      title: '任务类型',
      key: 'task_type',
      render(row) {
        const typeMap = {
          video_analysis: { label: '视频分析', color: 'success' },
          image_analysis: { label: '图片分析', color: 'info' },
        };
        const typeConfig = typeMap[row.task_type] || { label: row.task_type, color: 'default' };
        return h(NTag, { type: typeConfig.color }, typeConfig.label);
      },
    },
    {
      title: '设备ID',
      key: 'device_id',
    },
    {
      title: '视频流URL',
      key: 'rtsp_url',
    },
    {
      title: '算法ID',
      key: 'algorithm_id',
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h(NSpace, {}, [
          h(
            NButton,
            {
              size: 'small',
              type: row.status === '运行中' ? 'error' : 'primary',
              onClick: () => handleToggleStatus(row),
            },
            row.status === '运行中' ? '停用' : '启用'
          ),
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              onClick: () => handleDetail(row),
            },
            '详情'
          ),
          h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: () => handleDelete(row),
            },
            '删除'
          ),
        ]);
      },
    },
  ]);

  // 在handleSearch中也需要修改为调用接口搜索
  async function handleSearch() {
    try {
      loading.value = true;
      const res = await FetchTaskList({
        page: pagination.page,
        pageSize: pagination.pageSize,
        keyword: searchValue.value.trim(),
      });
      taskList.value = res.list.map((task) => ({
        id: task.id,
        name: task.name,
        status: task.status === 1 ? '运行中' : '已停用',
        task_mode: task.task_mode,
        task_type: task.task_type,
        device_id: task.device_id,
        rtsp_url: task.rtsp_url,
        algorithm_id: task.algorithm_id,
      }));

      pagination.itemCount = res.total;
    } catch (error) {
      message.error('搜索失败');
      taskList.value = [];
    } finally {
      loading.value = false;
    }
  }

  async function handleToggleStatus(row) {
    try {
      const status = row.status === '运行中' ? '停用' : '启用';
      // 调用 API 更新任务状态
      await UpdateTaskStatus(row.id, status);
      message.success(`${status}任务：${row.name}`);
      // 刷新任务列表
      getTaskList();
    } catch (error) {
      message.error('操作失败');
    }
  }

  function handleDetail(row) {
    selectedTask.value = row;
    showDetailDrawer.value = true;
  }

  async function handleDelete(row) {
    try {
      // 调用 API 删除任务
      await DeleteTask(row.id);
      message.success(`删除任务：${row.name}`);
      // 刷新任务列表
      getTaskList();
    } catch (error) {
      message.error('删除失败');
    }
  }
</script>
